package com.ruoyi.utils.qny;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.qiniu.http.Client;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.ruoyi.SSL.domain.SslApply;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUtils;
import com.tencentcloudapi.ssl.v20191205.models.Certificates;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class QnySslUtils {

    private static final String QNY_BASE_URI = "https://api.qiniu.com";

    public static Auth createAuth(String keyId, String keySecret) {
        return Auth.create(keyId, keySecret);
    }

    public static AjaxResult listSsl(String keyId, String keySecret, String sslName){
        try {
            Auth auth = createAuth(keyId, keySecret);
            StringMap headers = auth.authorizationV2(QNY_BASE_URI+"/sslcert?Limit=100", "GET", "".getBytes(), Client.FormMime);
            HttpRequest request = HttpRequest.get(QNY_BASE_URI+"/sslcert?Limit=100");
            request.header("Content-Type", Client.FormMime);
            request.header("X-Qiniu-Date", headers.map().get("X-Qiniu-Date").toString());
            request.header("Authorization", headers.map().get("Authorization").toString());
            HttpResponse response = request.execute();
            if(response.getStatus() == 200){
                JSONObject resultObj = JSONUtil.parseObj(response.body());
                List<JSONObject> resultObjList = JSONUtil.toList(resultObj.getStr("certs"), JSONObject.class);
                //返回数据
                return AjaxResult.success("查询七牛云证书列表成功！", resultObjList);
            }
        } catch (Exception e) {
            return AjaxResult.error("查询七牛云证书列表错误："+e.getMessage());
        }
        return AjaxResult.error("查询七牛云证书列表错误！");
    }


    public static AjaxResult uploadSsl(String keyId, String keySecret, SslApply sslApply, String ptName){
        try {
//            AjaxResult aj = listSsl(keyId, keySecret, "");
//            if(aj.isSuccess()){
                //查询为空就上传证书
//                if(StrUtil.isBlank(JSONUtil.toJsonStr(aj.get("data")))||JSONUtil.toList(JSONUtil.toJsonStr(aj.get("data")), Certificates.class).size() < 1){
                Auth auth = createAuth(keyId, keySecret);
                Map<String,Object> reqParam = new StringMap().map();
                reqParam.put("Name", sslApply.getCertificateDomain()+"_"+ptName+"_"+ RandomUtil.randomStringUpper(9));
                reqParam.put("CommonName", sslApply.getCertificateDomain());
                //重新计算信息  读取文件数据
                String[] fileArray = sslApply.getSslFilePath().split(",");
                reqParam.put("Pri", FileUtils.readFileContent(fileArray[0]));
                reqParam.put("Ca", FileUtils.readFileContent(fileArray[1]));
                StringMap headers = auth.authorizationV2(QNY_BASE_URI+"/sslcert", "POST", JSONUtil.toJsonStr(reqParam).getBytes(), Client.JsonMime);
                HttpRequest request = HttpRequest.post(QNY_BASE_URI+"/sslcert");
                request.header("Content-Type", Client.JsonMime);
                request.header("X-Qiniu-Date", headers.map().get("X-Qiniu-Date").toString());
                request.header("Authorization", headers.map().get("Authorization").toString());
                request.body(JSONUtil.toJsonStr(reqParam));
                HttpResponse response = request.execute();
                JSONObject resultObj = JSONUtil.parseObj(response.body());
                if(response.getStatus() == 200){
                    return AjaxResult.success("新增七牛云证书成功！", resultObj.getStr("certID"));
                }else{
                    return AjaxResult.error("新增七牛云证书失败："+resultObj.getStr("error"));
                }
//                }else{
//                    List<JSONObject> resultObjList = JSONUtil.toList(JSONUtil.toJsonStr(aj.get("data")), JSONObject.class);
//                    return AjaxResult.success("获取七牛云证书成功！", resultObjList.get(0).getStr("certID"));
//                }
//            }
//            return aj;
        } catch (Exception e) {
            return AjaxResult.error("新增七牛云证书错误："+e.getMessage());
        }
    }

    public static AjaxResult delSsl(String keyId, String keySecret, String certID){
        try {
            Auth auth = createAuth(keyId, keySecret);
            StringMap headers = auth.authorizationV2(QNY_BASE_URI+"/sslcert/"+ certID, "DELETE", "".getBytes(), Client.JsonMime);
            HttpRequest request = HttpRequest.delete(QNY_BASE_URI+"/sslcert/"+ certID);
            request.header("Content-Type", Client.JsonMime);
            request.header("X-Qiniu-Date", headers.map().get("X-Qiniu-Date").toString());
            request.header("Authorization", headers.map().get("Authorization").toString());
            HttpResponse response = request.execute();
            JSONObject resultObj = JSONUtil.parseObj(response.body());
            if(response.getStatus() == 200){
                return AjaxResult.success("删除证书成功！");
            }else{
                return AjaxResult.error("删除七牛云证书失败："+resultObj.getStr("error"));
            }
        } catch (Exception e) {
            return AjaxResult.error("删除七牛云证书错误："+e.getMessage());
        }
    }
}
